/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utfpr.cp.model;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author Adriano_2
 */
public class ResourceDataDAO extends DAO {

    public ResourceDataDAO(EntityManager em) {
        super(em);
    }
    
    public ResourceData getByUrl(String url) {
        Query q = em.createQuery("SELECT r FROM ResourceData r WHERE r.url.url = :url");
        q.setParameter("url", url);
        try {
            return (ResourceData) q.getSingleResult();
        } catch (NoResultException e) {
            //Logger.getLogger(Main.class.getName()).log(Level.OFF, null, e);
        }

        return new ResourceData();
    }
    
    public List<ResourceData> getResoursesToParser() {
        String subquery = "SELECT DISTINCT h.url FROM HTMLTag h";
        try {
            Query q = em.createQuery("SELECT r FROM ResourceData r WHERE r.type = :type AND r.url NOT IN (" + subquery + ") ");
            q.setParameter("type", ResourceType.HTML);
            q.setMaxResults(100);
            return q.getResultList();
        }
        catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
    
    public long getTotalPages() {
         try {
            Query q = em.createQuery("SELECT count(p) FROM ResourceData p");
            return ((Long) q.getSingleResult() ).longValue();
        }
        catch (Exception e) {
            return -1;
        }
    }
    
    public long getTotalHeaders() {
         try {
            Query q = em.createQuery("select count(*) from ResourceData p inner join p.headers h ");
            return ((Long) q.getSingleResult() ).longValue();
        }
        catch (Exception e) {
            return -1;
        }
    }
    
    public long getTotalResoursesToParser() {
        String subquery = "SELECT DISTINCT h.url FROM HTMLTag h";
        try {
            Query q = em.createQuery("SELECT count(r) FROM ResourceData r WHERE r.type = :type AND r.url NOT IN (" + subquery + ") ");
            q.setParameter("type", ResourceType.HTML);
            return ((Long) q.getSingleResult() ).longValue();
        }
        catch (Exception e) {
            return -1;
        }
    }
    
    public static ResourceDataDAO factory() {
        return new ResourceDataDAO(getEntity());
    }

}
